home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
500 MB Nyheder Direkte fra Internet 2
/
500 MB nyheder direkte fra internet CD 2.iso
/
start
/
data
/
text
/
c.txt
< prev
next >
Wrap
Text File
|
1994-09-21
|
43KB
|
942 lines
FUN
C is a computer language invented by Dennis Ritchie in 1972,
while he was working for AT&T at Bell Labs. He called it ``C''
because it came after ``B'', which was an earlier language
developed by a colleague.
Earlier chapters of The Secret Guide to Computers explained how
to program in BASIC and PASCAL. C resembles those languages but
has two advantages: C runs faster and consumes less RAM.
C has become the most popular language for creating advanced
programs. The world's largest software companies have switched to
C from assembly language:
Created using assembly lang.Created using C
DBASE 2 DBASE 3, 3+, 4, and 5
Word Perfect 4.0, 4.1, and 4.2Word Perfect 5, 5.1, and 6
1-2-3 release 1, 1A, 2, 2.01, 2.2, 2.3, 2.41-2-3 release 3, 3.1,
3.2, 3.3, 3.4
If you become an expert C programmer, you can help run those
rich software companies and get rich yourself!
Before studying C, study BASIC and PASCAL, which are similar
but easier.
Unlike BASIC and PASCAL, C lets you easily create a pointer,
which is a note about which part of RAM to use. If you create the
pointer incorrectly, C will use the wrong part of RAM ___ and
erase whatever information had been there before. For example, C
might erase the part of RAM used by DOS, so that DOS becomes
confused and accidentally erases your disks!
A faulty pointer (which points to the wrong part of RAM) is
called a runaway pointer, and it's a C programmer's greatest
fear. Even if your innocent-looking program doesn't seem to
mention pointers, a small error in your program might make C
create a pointer that wrecks your computer. That's why many C
programmers look thin and haggard and bite their nails. To keep
your nails looking pretty, make backup copies of your floppy and
hard disks before trying to program in C.
C is like a sports car with no brakes: it's fast, fun, slim,
sleek, and dangerous. If you program in C, your friends will
admire you and even whistle at you as you zoom along the freeway
of computer heaven; but if you're not careful, your programs and
disks will crash, and so will your career!
Versions of C
For the IBM PC, the
nicest kinds of C are Quick C and Turbo C.
Quick C, published by
Microsoft, lists for $99. You can buy it from discount dealers
for just $59. Another way to get Quick C is to buy a combination
package called Quick C with Quick Assembler. Discount dealers
sell that combo for $139. Another combo is called the Microsoft C
package: it contains Quick C and also an optimizing version of C
(which produces programs that run faster). Discount dealers sell
it for $293.
Turbo C is published by
Borland. Although it's slightly harder to use than Quick C, many
programmers prefer it because it runs much faster, consumes less
RAM and disk space, comes with better instruction manuals,
handles advanced topics more simply, and can be copied more
easily onto your hard disk.
C++ You can buy a
variant of C called C++. It's harder to learn than C. It lets you
use an advanced technique called object-oriented programming
(OOP), in which you define ``objects'' and give those objects
``properties''.
To explore C++, get
Microsoft's Visual C++ for Windows ($75) or Borland's Turbo C++
($67 for the DOS version, $74 for the Windows version). Those are
the prices charged by discount dealers such as Computer Discount
Warehouse (800-454-4CDW).
When you buy Turbo C++,
you get a free copy of Turbo C, so you get both languages for a
low total price!
Mac The best version of
C for the Mac is Think C. It's published by the Lightspeed
division of Symantec. You can get it for $165 from discount
dealers such as Mac Connection.
Where to begin Since C++
is harder than C, begin by learning C. Here's how to use Quick C
(version 2) and Turbo C (version 2).
Copy to the hard disk
Turbo C and Quick C come
on floppy disks, which you should copy to your hard disk. Here's
how.
Turn on the computer
without any floppy in drive A. As I explained in the MS-DOS
chapter, make sure your hard disk contains a CONFIG.SYS file
saying ``files=20'' (or a bigger number) and ``buffers=10'' (or a
bigger number).
Here's what to do next.
Turbo C Turbo C comes on
six 5¼-inch floppy disks. When you see the C prompt, put the
Turbo C Install/Help Disk in drive A and type ``a:''. The
computer displays an A prompt.
Type ``install''. The
computer says ``Turbo C Installation Utility''.
Press ENTER three times.
The computer says ``Turbo C Directory''. Press the F9 key.
When the computer tells
you, put the other Turbo C disks in drive A and press ENTER.
The computer says
``Turbo C is now installed on your system.'' Ignore the
computer's comments about PATH. Press ENTER.
Turn off the computer, so you can start fresh.
Quick C Quick C comes on ten 5¼-inch floppy disks. Put the
Quick C Setup Disk in drive A and type ``a:''. The computer
displays an A prompt.
Type ``setup''. The computer says ``Microsoft Quick C Setup
Program''. Press ENTER ten times.
The computer asks, ``Include in combined libraries?'' The
computer is asking whether you're planning to write programs that
include graphics. Most C programs do not use graphics; most C
courses do not discuss graphics; this chapter does not discuss
graphics. Chapter 12 of the Quick C instruction manual does
discuss graphics. If you plan to study and use graphics, press Y
and ENTER, then Y again and ENTER (which makes the computer copy
graphics commands to the hard disk); otherwise, press ENTER twice
(so the computer doesn't bother copying graphics commands to the
hard disk, and your hard disk won't be so full).
The computer asks, ``Do you want to change any of the above
options?'' Press N and ENTER.
The computer asks, ``Install Microsoft Mouse?'' If you have a
Microsoft Mouse (or clone), press ENTER; if you have no mouse or
a different brand, press N then ENTER.
Press ENTER four more times. The computer asks again, ``Do you
want to change any of the above options?'' Press N and ENTER.
Press ENTER eight more times. The computer asks again, ``Do you
want to change any of the above options?'' Press N and ENTER.
Press ENTER again. When the computer tells you, put other Quick
C disks in drive A press ENTER.
The computer says, ``Press any key to start building combined
libraries.'' Press ENTER twice. Ignore the computer's comments
about ``creating sample configuration files''.
You'll see an A prompt. Type ``copy con c:\qc2\qc2.bat'' (and
press ENTER at the end of that command). Underneath that command,
type this:
set lib=\qc2\lib
set include=\qc2\include
cd bin
qc
cd \
Underneath all that, press the F6 key then ENTER.
Turn off the computer, so you can start fresh.
Start C
To start using C, turn on the computer without any floppy in
drive A.
To do Turbo C, type ``do tc''. To do Quick C, type ``do qc2''.
(That ``do'' method works if you put the DO.BAT file onto your
hard disk as I recommended in the MS-DOS chapter. If you have not
put DO.BAT onto your hard disk, do Turbo C by typing ``cd tc''
and then ``tc''; do Quick C by typing ``cd qc2'' and then
``qc2''.)
If you're using Turbo C, then press F10.
Type your program
For example, type this C
program:
main(){
puts("make your nose");
puts("touch your toes");
}
The program begins by
saying ``main()'', which means: here comes the main program.
Do not capitalize the
word ``main''. If you type ``MAIN'' instead of ``main'', the
computer will gripe. In C, you must type all commands by using
lower-case letters, not capitals.
After the ``main()'',
the rest of the program is enclosed in braces: {}. Like PASCAL's
``BEGIN'' and ``END'', they mark the beginning and end of the
program.
The lines between the
braces are indented. To indent, tap the TAB key. The indentation
is optional but helps other programmers understand your program.
Once you've indented a
line, the computer automatically indents all the lines underneath
it. (If the computer automatically indents a line that you don't
want to indent, press the BACKSPACE key.)
The indented lines tell
the computer to print two strings: ``make your nose'' and ``touch
your toes''.
Notice that C says
``puts'' instead of ``print''. (BASIC says PRINT; PASCAL says
WRITELN; C says ``puts'' instead.) The command ``puts'' means:
put the string onto your screen.
After ``puts'', you must
put parentheses. (PASCAL's WRITELN requires parentheses also.)
Like BASIC, C makes you
put each string in quotation marks.
Like PASCAL, C requires
a semicolon at the end of each typical line. Here's the rule:
each line of C should end with a semicolon or brace.
Run the program
When you finish typing
the program, tell the computer to run it. Here's how: for Turbo
C, press F10 then type RR; for Quick C, press F5 and if the
computer asks ``Rebuild?'' press ENTER.
If you typed the program
wrong, the computer will say ERRORS. (If you're using Turbo C,
then press ENTER and F6.) Correct the error, then tell the
computer to run the program again.
When the computer runs
the program correctly, the computer prints:
make your nose
touch your toes
(If you're using Turbo C, that printing flashes on the screen too
briefly for you to read; after the flash, press Alt with F5,
which makes the printing reappear.)
After the computer's run
the program successfully and you've read what the computer
printed, press ENTER.
Manipulate your program
Here's how to manipulate your program.
Turbo C Turbo C lets you manipulate your program in the same
way as Turbo PASCAL 5.5. For details, read the explanation of
Turbo PASCAL 5.5 on pages 391-392. On those pages, read the
sections entitled ``Advanced editing'', ``Save your program'',
``Switch programs'', and ``Exit''.
Quick C Quick C lets you manipulate your program in the same
way as Quick PASCAL. For details, read the explanation of Quick
PASCAL on pages 385-386. On those pages, read just the sections
entitled ``Advanced editing'' and ``Save your program''.
Here's how to do further manipulations in Quick C. . . .
Save your program. To copy your program to the hard disk, press
the Alt key then say ``File Save'' (by typing FS). If the
computer says ``File Name'', type a name for the program (such as
NOSE) and press ENTER. If you called the program ``NOSE'', the
computer will put the program onto the hard disk as ``NOSE.C''.
(It will be in the BIN subdirectory of the QC2 subdirectory.)
Erase the screen. To erase the screen so you can start writing
a new program, press the Alt key then say ``File New'' (by typing
FN). If the computer asks ``Do you want to save?'', press N.
Retrieve a program. To retrieve a saved program, press the Alt
key then say ``File Open'' (by typing FO). Type the program's
name (such as NOSE) and press ENTER. If the computer asks ``Do
you want to save?'', press N.
Exit. When you finish using Quick C, here's how to return to
the DOS prompt. Press the Alt key. Say ``File eXit'' (by typing
FX). If the computer asks ``Do you want to save?'', press N.
Many versions
Suppose you write a program, save it as ``NOSE'', and then run
it. Your hard disk will contain several versions of NOSE.
The first version, NOSE.C, is the program you typed. Turbo C
puts NOSE.C in the TC subdirectory; Quick C puts NOSE.C in the
BIN subdirectory of the QC2 subdirectory.
When you say to run, the computer automatically creates and
runs NOSE.EXE, which is the Executable machine-language version
of your program. After you quit C, you can run NOSE.EXE by typing
``cd \tc'' (for Turbo C) or ``cd \qc2\bin'' (for Quick C) and
then typing ``nose''.
You can erase the version called NOSE.OBJ. The computer creates
it just to help create NOSE.EXE.
Quick C creates three extra files (NOSE.MDT, NOSE.ILK, and
NOSE.SYM), which you can erase.
\n
Here's a short cut.
Instead of typing ___
main(){
puts("make your nose");
puts("touch your toes");
}
you can type:
main(){
puts("make your nose\ntouch your toes");
}
The symbol \n means: new line. It tells the computer to press the
ENTER key. So puts(``make your nose\ntouch your toes'') tells the
computer to print ``make your nose'', then press the ENTER key,
then print ``touch your toes''. The computer will print:
make your nose
touch your toes
When you type the symbol
\n, make sure you type a backslash: \. Do not type a division
sign: /.
Printf
Instead of saying
``puts'', you can say ``printf'', like this:
main(){
printf("I love her so");
printf("up in the morning");
}
The command ``printf''
means: perform the print function. That program makes the
computer print ``I love her so'' and ``up in the morning'' on the
same line as each other, so the computer will print:
I love her soup in the morning
To force printf to press
the ENTER key after ``I love her so'', say \n, like this:
main(){
printf("I love her so\n");
printf("up in the morning");
}
That makes the computer print:
I love her so
up in the morning
``Printf'' differs from
``puts'' in two ways:
Printf doesn't make the computer press the ENTER key (unless you
say \n).
Puts handles just strings. Printf is fancier: it can handle
numbers also. Since printf is fancier, it requires more RAM than
puts.
MATH
If you have 750 apples and buy 12 more, how many apples will
you have altogether? This program prints the answer:
main(){
printf("you will have %d apples",750+12);
}
In the second line, the %d means: a bunch of digits. The
computer will print ``you will have'', then a bunch of digits,
then ``apples''. The ``bunch of digits'' will be the answer to
750+12. Altogether, the computer will print:
you will have 762 apples
In C, each printf line begins with a string (such as ``you will
have %d apples'') and typically ends with a computation (such as
750+12). The computer automatically inserts the computation's
answer into the string.
If you omit the words ``you will have'' and ``apples'', like
this ___
main(){
printf("%d",750+12);
}
the computer will print just the number 762. In that program, if
you forget the ``%d'' or forget to say printf instead of puts,
the computer will print wrong answers.
To print two answers on the same line, say %d twice:
main(){
printf("%d %d", 21+4, 68+1);
}
That program makes the computer print both answers:
25 69
The computer leaves a space between the answers because of the
space between the %d's. If you omit the space between the %d's
and say ``%d%d'' instead, the computer will print:
2569
Like BASIC and PASCAL, C lets you use the symbols +, -, *, /,
parentheses, decimal points, and e notation. But if you're not
careful, the computer will print wrong answers. Here's why. . . .
Integers versus double precision
C handles two types of numbers well.
One type of number is called an integer (or int). An int
contains no decimal point and no e. For example, -27 and 30000
are ints.
The other type of number that C handles well is called a
double-precision number (or a double). A double contains a
decimal point or an e. For example, -27.0 and 3e4 are doubles.
You can abbreviate: instead of writing ``-27.0'', you can write
``-27.'', and instead of writing ``0.37'' you can write ``.37''.
To print an int, say ``%d'' in the printf statement. To print a
double, say ``%.15g'' instead. (The .15 makes the computer print
15 significant digits, and the g makes it use a general method of
printing.)
Largest and tiniest numbers
The largest permissible int is 32767. The lowest is -32768.
If you feed the computer an int that's too large, the computer
won't complain. Instead, the computer will print a wrong answer!
The largest permissible
double is approximately 1.7e308. The tiniest is approximately
1.7e-308.
Tricky arithmetic
If you combine ints, the
answer is an int. For example, 2+3 is this int: 5.
11/4 is this int: 2.
(11/4 is not 2.75.)
If you combine doubles,
the answer is a double. If you combine an int with a double, the
answer is a double.
How much is 200*300?
Theoretically, the answer should be this int: 60000. But since
60000 is too large to be an int, the computer will print a wrong
answer. To make the computer multiply 200 by 300 correctly, ask
for 200.0*300.0, like this:
main(){
printf("%.15g",200.0*300.0);
}
That program makes the computer get the correct answer, 60000.0.
The computer won't bother printing the ``.0''; it will print:
60000
Advanced math
The computer can do
advanced math. For example, it can compute square roots. This
program makes the computer print the square root of 9:
#include <math.h>
main(){
printf("%.15g",sqrt(9.0));
}
The computer will print 3.
Say sqrt(9.0) rather
than sqrt(9), because the number you find the square root of
should be double-precision, not an integer. If you make the
mistake of saying sqrt(9), Turbo C and Quick C will print the
correct answer but slowly; older versions of C will print a wrong
answer.
That program's top line
tells the computer to include a math heading. Begin that line by
typing the symbol #, and end with the symbol > instead of a
semicolon or brace. That line makes the computer use a file
called MATH.H, which is in a subdirectory called INCLUDE, which
is part of your C subdirectory. That MATH.H file tells the
computer to make advanced-math answers be double-precision.
If you forget to say
#include <math.h>, the computer will ignore MATH.H, think
advanced-math answers are integers, and print wrong answers.
Besides sqrt, you can
use other advanced math functions. All advanced-math functions
require that you use double-precision numbers and say #include
<math.h>. Here's a list of those advanced-math functions.
To handle exponents, you
can use sqrt (square root), exp (exponential power of e), log
(logarithm base e), and log10 (logarithm base 10). You can also
use pow: for example, pow(3.0,2.0) is 3.0 raised to the 2.0
power.
For trigonometry, you
can use sin (sine), cos (cosine), tan (tangent), asin (arcsin),
acos (arccosine), atan (arctangent), sinh (sine hyperbolic), cosh
(cosine hyperbolic), and tanh (tangent hyperbolic). You can also
use atan2: for example, atan2(y,x) is the arctangent of y divided
by x.
For absolute value, use
fabs (floating absolute). For example, fabs(-2.3) is 2.3.
To round, use floor
(which rounds down) or ceil (which stands for ``ceiling'' and
rounds up). For example, floor(26.319) is 26.000, and
ceil(26.319) is 27.000.
NUMERIC VARIABLES
Like BASIC, C lets you use variables. For example, you can say:
n=3;
A variable's name can be short (such as n) or long (such as
town_population_in_1988). The name must begin with a letter. The
name can contain letters, digits, and underlines, but not blank
spaces. The computer looks at just the first eight characters and
ignores the rest, so the computer considers
town_population_in_1988 to be the same as town_pop.
At the top of your program, say what type of number the
variable stands for. For example, if n and
town_population_in_1988 will stand for numbers that are ints and
mortgage_rate will stand for a double, begin your program by
saying:
main(){
int n,town_population_in_1988;
double mortgage_rate;
Here's a short cut. Instead of beginning your program by saying
___
main(){
int n;
n=3;
just say:
main(){
int n=3;
If you're writing a program in which n starts at 3 and
population_in_1988 starts at 21000, begin your program by saying:
main(){
int n=3, population_in_1988=21000;
Increasing & decreasing
The symbol ++ means
``increase''. For example, ++n means ``increase n''. If you say
___
main(){
int n=3;
++n;
printf("%d",n);
}
the n starts at 3 and increases to 4, so the computer prints 4.
Saying ++n gives the
same answer as n=n+1, but the computer handles ++n faster.
The symbol ++ increases
the number by 1, even if the number is a decimal. For example, if
x is 17.4 and you say ++x, the x will become 18.4.
The opposite of ++ is
--. The symbol -- means ``decrease''. For example, --n means
``decrease n''. Saying --n gives the same answer as n=n-1 but
faster.
Strange short cuts
If you use the following
short cuts, your programs will be briefer and run faster.
Instead of saying n=n+2,
say n+=2, which means ``n's increase is 2''. Similarly, instead
of saying n=n*3, say n*=3, which means ``n's multiplier is 3''.
Instead of saying ++n
and then giving another command, say ++n in the middle of the
other command. For example, instead of saying ___
++n;
j=7*n;
say:
j=7*++n;
That's pronounced: ``j is 7 times an increased n''. So if n was
2, saying j=7*++n makes n become 3 and j become 21.
Notice that when you say
j=7*++n, the computer increases n before computing j. If you say
j=7*n++ instead, the computer increases n after computing j; so
j=7*n++ has the same effect as saying:
j=7*n;
++n;
How to input
This program predicts how old you'll be ten years from now:
Program Meaning
main(){
int age; The age is an integer.
printf("How old are you? "); Ask ``How old are you?
''.
scanf("%d",&age); Wait for person to
input age.
printf("Ten years from now, you'll be %d years
old.",age+10); Give result.
}
Notice that in the scanf statement, you must say &age instead of
age. (If you forget the symbol &, you'll have a runaway pointer
___ and a disaster!) Here's a sample run:
How old are you? 27
Ten years from now, you'll be 37 years old.
The next program converts feet to inches. It even handles
decimals: it can convert 1.5 feet to 18.0 inches.
Program Meaning
main(){
double feet; The number of feet is
double-precision.
printf("How many feet? ");Ask ``How many feet? ''.
scanf("%lf",&feet); Wait for person to input how
many feet.
printf("That makes %.15g inches.",feet*12.0);Print the
result.
}
Notice that to input a double-precision number, the scanf
statement must say ``%lf'', which means ``long floating-point'',
which is a fancy way of saying ``double precision''.
Arrays
Like BASIC and PASCAL, C lets you create arrays. For example,
if you want x to be a list of 3 double-precision numbers, begin
your program by saying:
double x[3];
That says x will be a list of 3 double-precision numbers, called
x[0], x[1], and x[2]. Notice that C starts counting at 0. (PASCAL
starts counting at 1 instead; PASCAL would call those numbers
x[1], x[2], and x[3].)
Here's a complete C program using that array:
main(){
double x[3];
x[0]=10.6;
x[1]=3.2;
x[2]=1.1;
printf("%.15g",x[0]+x[1]+x[2]);
}
The computer will print the sum, 14.9.
Notice that if you say double x[3], you can refer to x[0],
x[1], and x[2], but not x[3]. If you accidentally refer to x[3],
you'll be creating a runaway pointer.
If you want x to be a table having 2 rows and 3 columns of
double-precision numbers, begin your program by saying:
main(){
double x[2][3];
Notice that C says x[2][3]. (PASCAL says x[2,3] instead.) In C,
if you accidentally say x[2,3] instead of x[2][3], you'll have a
runaway pointer.
Since C always starts counting at 0 (not 1), the number in the
table's upper-left corner is called x[0][0].
CHARACTER VARIABLES
A variable can stand for a character. For example, suppose
you're in school, take a test, and get an A on it. To proclaim
your grade, write a program containing this line:
grade='A';
Here's the complete program:
Program Meaning
#include <stdio.h>INCLUDE the STanDard I/O Headers.
main(){
char grade;The grade is a character.
grade='A';The grade is `A'.
putchar(grade);Print the character that's the grade.
}
The computer will print:
A
The usual way to print the grade is to say putchar(grade). To
teach the computer what putchar means, say #include <stdio.h>.
Another way to print the grade is to say printf(``%c'',grade);
the ``%c'' means ``character''.
To input a grade, say scanf(``%c'',&grade) or grade=getchar().
If you say scanf(``%c'',&grade), the user must press the ENTER
key after entering the grade. If you say grade=getchar() instead,
the user doesn't have to press ENTER. Like putchar, getchar
requires you to say #include <stdio.h>.
Strings of characters
A variable can stand for a whole string of characters:
Program Meaning
main(){
char *torture; Torture is a whole string of characters.
torture="slice off your head";Here's torture.
puts(torture); Print the string that's torture.
}
The computer will print:
slice off your head
That program begins by saying char *torture. The * means
``string'', so that char * means ``character string''. If you
omit the *, torture will be just one character instead of a
string of characters.
Put each string (such as ``slice off your head'') in
double-quotes ("). Put a single character (such as `A') in
single-quotes (').
To print a string, say puts. To print a single character, say
putchar.
The usual way to print the torture string is to say
puts(torture). Another way is to say printf(``%s'',torture); the
``%s'' means ``string''.
Gets Here's how to input a string:
main(){
char *name; name=(char *)malloc(41);
printf("What is your name? ");
gets(name);
printf("I like the name %s",name);
}
Here's a sample run of that program:
What is your name? Maria Gonzales
I like the name Maria Gonzales
In that program, the most important line is ``gets(name)''.
That tells the computer to get a string from the user; it lets
the user input a name. Notice that to input a string instead of a
number, you say ``gets'' instead of ``scanf''.
Malloc In that program, the top line says ``name=(char
*)malloc(41)''. That warns the computer that the person's name
might consume up to 41 characters in RAM (40 bytes for the name
itself, plus 1 byte for the end-of-string marker). It makes the
computer reserve 41 bytes of RAM for the name. The ``malloc''
means ``memory allocation''. If you forget to say ``name=(char
*)malloc(41)'', you'll have a runaway pointer.
To be extra safe, in case the person types an extra-long name,
you might be better off saying malloc(51) or even malloc(81).
Since most strings in most programs are less than 81 characters
long, here's a rule of thumb: to be safe, say malloc(81) for each
string.
In the program that says torture=``slice off your head'', you
don't have to say torture=(char *)malloc(20), because when the
computer sees ``slice off your head'' in your program, the
computer automatically reserves 20 bytes of RAM to hold it. You
need malloc just for variables that are input or that are built
up by combining other variables.
Substrings If torture is ``slice off your head'', torture+1
means ``torture without the first character''; it is ``lice off
your head''. Similarly, torture+2 is ``torture without the first
2 characters''; it is ``ice off your head''.
(Technically, torture+2 means ``the string that begins 2
characters past the beginning of torture''; it's ``the string
whose starting memory address is 2 higher than torture's''.)
For example:
Program Meaning
main(){
char *torture; Torture is a whole string of characters.
torture="slice off your head";Here's torture.
printf("%s",torture+2);Print ``ice off your head''.
}
Here's how to make cool be torture+2, which is ``ice off your
head'':
Program Meaning
main(){
char *torture,*cool;Torture and cool are strings.
torture="slice off your head";Here's torture.
cool=torture+2; Cool is ``ice off your head''.
printf("%s",cool);Print ``ice off your head''.
}
Since cool uses the same part of RAM as torture, cool doesn't
have to be malloc'ed.
Extracting a character from a string If torture is ``slice off
your head'', *torture indicates the first character in torture;
it is `s'. This program makes the computer print the `s':
Program Meaning
#include <stdio.h> Include the definition of putchar, etc.
main(){
char *torture,hiss;Torture's a string. Hiss is a
character.
torture="slice off your head";Here's torture.
hiss=*torture; Hiss is torture's first character, `s'.
putchar(hiss); Print `s'.
}
If you want to print just torture's third character (which is
the i), ask for *(torture+2), which means ``the character in
torture beyond the first 2''; or just ask for torture[2].
Suppose torture's a string, and you say cool=torture. If you
change cool's third character to an x (by saying cool[2]=`x'),
you'll also be changing the third character of torture, since
cool and torture share characters with each other and share the
same part of RAM.
LOGIC
Like most computer languages, C lets you say ``if'', ``while'',
``for'', and ``goto'' and create comments and subroutines. Here's
how. . . .
If
If a person's age is less than 18, let's make the computer say
``You are still a minor.'' Here's the fundamental line:
if (age<18) puts ("You are still a minor.");
Notice you must put parentheses after the word ``if''.
If a person's age is less than 18, let's make the computer say
``You are still a minor.'' and also say ``Ah, the joys of
youth!'' and ``I wish I could be as young as you!'' Here's how to
say all that:
if (age<18){
puts("You are still a minor.");
puts("Ah, the joys of youth!");
puts("I wish I could be as young as you!");
}
Let's put that structure into a complete program:
main(){
int age;
printf("how old are you? ");
scanf("%d",&age);
if (age<18){
puts("You are still a minor.");
puts("Ah, the joys of youth!");
puts("I wish I could be as young as you!");
}
else{
puts("You are an adult.");
puts("Now we can have some adult fun!");
}
puts("Glad to have met you.");
}
If the person's age is less than 18, the computer will print
``You are still a minor.'' and ``Ah, the joys of youth!'' and ``I
wish I could be as young as you!'' If the person's age is not
less than 18, the computer will print ``You are an adult.'' and
``Now we can have some adult fun!'' Regardless of the person's
age, the computer will end the conversation by saying ``Glad to
have met you.''
The ``if'' statement uses this notation:
Notation Meaning
if (age<18){ if age is less than 18
if (age<=18){ if age is less than or equal to 18
if (age==18){ if age is equal to 18
if (age!=18){ if age is not equal to 18
if (age<18 && weight>200){if age<18 and weight>200
if (age<18 || weight>200){if age<18 or weight>200
Look at that table carefully! Notice that in the ``if''
statement, you must use double symbols: you must say ``==''
instead of ``='', say ``&&'' instead of ``&'', and say ``||''
instead of ``|''. If you accidentally use single symbols instead
of double, the computer will print wrong answers.
Strings To put strings in an ``if'' statement, you must say
``strcmp'', which warns the computer to do a ``string
comparison''.
For example, suppose x and y are strings, and you want to test
whether they're equal. Do not say ``if (x==y)''. Instead, say
``if (strcmp(x,y)==0)'', which means ``if string comparison
between x and y shows 0 difference between them''.
To test whether x's
string comes before y's in the dictionary, do not say ``if
(x<y)''. Instead, say ``if (strcmp(x,y)<0)''.
While
Let's make the computer
print the word ``love'' repeatedly, like this:
love love love love love love love love love love love etc. love
love love love love love love love love love love etc.
love love love love love love love love love love love etc.
etc.
This program does it:
main(){
while (1) printf("love ");
}
In that program, the
``while (1)'' means: do repeatedly. The computer will do
printf(``love'') repeatedly, looping forever ___ or until you
abort the program.
Let's make the computer
start at 20 and keep counting, so the computer will print:
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 etc.
This program does it:
Program
Meaning
main(){
int i=20; Start
the integer i at 20.
while (1){ Repeat
these lines forever:
printf("%d ",i);
print i
++i;
increase i
}
}
In that program, if you
say ``while (i<30)'' instead of ``while (1)'', the computer will
do the loop only while i remains less than 30; the computer will
print just:
20 21 22 23 24 25 26 27 28 29
Instead of saying
``while (i<30)'', you can say ``while (i<=29)''.
For
Here's a more natural
way to get that output of numbers from 20 to 29:
main(){
int i;
for (i=20; i<=29; ++i) printf("%d ",i);
}
In that program, the
``for (i=20; i<=29; ++i)'' means ``Do repeatedly. Start with
i=20, and keep repeating as long as i<=29. At the end of each
repetition, do ++i.''
In that ``for''
statement, if you change the ++i to i+=3, the computer will
increase i by 3 instead of by 1, so that the computer will print:
20 23 26 29
The ``for'' statement is
quite flexible. You can even say ``for (i=20; i<100; i*=2)'',
which makes i start at 20 and keep doubling, so the computer
prints:
20 40 80
Like ``if'' and
``while'', the ``for'' statement can sit atop a group of indented
lines that are in braces.
Goto
You can say ``goto''. For example, if you say ``goto yummy'',
the computer will go to the line whose name is yummy:
main(){
puts("my dog");
goto yummy;
puts("never");
yummy: puts("drinks whiskey");
}
The computer will print:
my dog
drinks whiskey
Comments
To put a comment in your program, begin the comment with the
symbol /* and end it with */. Here's an example:
/* The following program
is fishy */
main(){
puts("Our funny God"); /* notice religious motif */
puts("invented cod"); /* said by nasty flounder */
}
The computer will print just:
Our funny God
invented cod
Subroutines
Like PASCAL, C lets you invent subroutines and give them names.
For example, here's how to invent a subroutine called ``insult''
and use it in the main routine:
Program Meaning
main(){ Here's main routine:
puts("We all know...");print ``We all know...''
insult(); do the insult
puts("...but we love you");print the ending
}
insult(){ How to insult:
puts("you are stupid");print ``you are stupid''
puts("you are ugly");print ``you are ugly''
}
The computer will print:
We all know...
you are stupid
you are ugly
...but we love you
Like BASIC, C wants you to type the main routine first, then
the definition of the subroutine (called ``insult'').
Whenever you write a subroutine's name, you must put
parentheses afterwards, like this: insult(). Those parentheses
tell the computer: insult's a subroutine, not a variable.
Here's another example:
Program Meaning
main(){ The main routine says
laugh(); to laugh.
}
laugh(){ Here's how to laugh:
int i; print ``ha'' 100 times.
for (i=1; i<=100; ++i) printf("ha ");
}
The main routine says to laugh. The subroutine defines ``laugh''
to mean: print ``ha '' a hundred times. Notice that the ``int i''
is in the subroutine, not the main routine.
Let's create a more
flexible subroutine, so that whenever the main routine says
laugh(2), the computer will print ``ha ha''; whenever the main
routine says laugh(5), the computer will print ``ha ha ha ha
ha''; and so on. Here's how:
main(){
puts("Here is a short laugh");
laugh(2);
puts("\nHere is a longer laugh");
laugh(5);
}
laugh(int n){
Here's how to laugh(n):
int i;
print ``ha'', n times.
for (i=1; i<=n; ++i) printf("ha ");
}
Average Let's define the
``average'' of a pair of integers, so that ``average(3,7)'' means
the average of 3 and 7 (which is 5), and so a main routine saying
``i=average(3,7)'' makes i be 5.
This subroutine defines
the ``average'' of all pairs of integers:
average(int a, int b){
return ((a+b)/2);
}
The top line says, ``Here's how to find the average of any two
integers, a and b.'' The next line says, ``Return to the main
routine, with this answer: (a+b)/2.''
Notice that the word
``return'' must be followed by parentheses.
Double-precision average
Let's revise the subroutine, to make it handle double-precision
numbers instead of integers, so a main routine saying
``x=average(3.0,7.0)'' makes x be 5.0.
Here's how:
double average(double a, double b){
return ((a+b)/2.0);
}
The subroutine begins by saying ``double average''. That says the
average will be a double-precision number. If you omit the word
``double'' and say just ``average'', the computer will make the
average be an integer instead, because the computer assumes all
subroutine answers are integers, unless you specifically say
``double'' or ``char'' or some other alternative.
So to get a
double-precision answer, you must begin the subroutine by saying
``double''. You must also say ``double'' in the main routine:
main(){
double x,average();
x=average(3.0,7.0);
printf("%.15g",x);
}